package com.lky.marshallmall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lky.common.to.mq.StockLockedTo;
import com.lky.common.to.mq.WareOrderTaskDetailTo;
import com.lky.common.utils.PageUtils;
import com.lky.common.utils.Query;
import com.lky.common.utils.R;
import com.lky.marshallmall.ware.dao.WareSkuDao;
import com.lky.marshallmall.ware.entity.WareOrderTaskDetailEntity;
import com.lky.marshallmall.ware.entity.WareOrderTaskEntity;
import com.lky.marshallmall.ware.entity.WareSkuEntity;
import com.lky.marshallmall.ware.exception.NoStockException;
import com.lky.marshallmall.ware.feign.OrderFeignService;
import com.lky.marshallmall.ware.feign.ProductFeignService;
import com.lky.marshallmall.ware.service.WareOrderTaskDetailService;
import com.lky.marshallmall.ware.service.WareOrderTaskService;
import com.lky.marshallmall.ware.service.WareSkuService;
import com.lky.marshallmall.ware.vo.OrderItemVo;
import com.lky.marshallmall.ware.vo.OrderVo;
import com.lky.marshallmall.ware.vo.SkuHashStockVo;
import com.lky.marshallmall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao skuDao;
    @Autowired
    private ProductFeignService feignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private OrderFeignService orderFeignService;





    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty((String) params.get("skuId"))) {
            wrapper.eq("sku_id", (String) params.get("skuId"));
        }
        if (!StringUtils.isEmpty((String) params.get("wareId"))) {
            wrapper.eq("ware_id", (String) params.get("wareId"));
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断还没有该库存记录，新增
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>()
                .eq( "sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku名字 如果失败整个事务无需回滚
            try {
                R info = feignService.info(skuId);
                if (info.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            this.baseMapper.insert(wareSkuEntity);
        } else {
            skuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHashStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHashStockVo> collectRes = skuIds.stream().map(sku -> {
            SkuHashStockVo skuHashStockVo = new SkuHashStockVo();
            //查询当前sku的总库存量
            Long count = this.baseMapper.getStock(sku);
            skuHashStockVo.setSkuId(sku);
            skuHashStockVo.setHasStock(count != null && (count > 0));
            return skuHashStockVo;
        }).collect(Collectors.toList());
        return collectRes;
    }

    /**
     * 为某个订单锁定库存
     * 下订单成功，没有支付订单过期被系统自动取消，被用户手动取消，都要解锁库存
     * 下订单成功，库存也成功，接下来的业务调用失败，导致订单回滚，所以也需要解锁库存
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单的详情 ->追溯
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //1.找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            //查询商品在哪里有库存
            List<Long> wareIds = skuDao.selectListWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            return stock;
        }).collect(Collectors.toList());

        Boolean allLock = true;

        //2.锁定库存
        for (SkuWareHasStock stock : collect) {
            Boolean skuStocked = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            //即使锁定失败，前面保存的工作单信息就会回滚，即使消息发出去，由于去数据库查不到id所以不用解锁。
            for (Long wareId : wareIds) {
                //成功返回1，否则为0
                Integer lockRes = skuDao.lockSkuStock(skuId, wareId, stock.getNum());
                if (lockRes == 1){
                    skuStocked = true;
                    //todo 告诉mq库存锁定成功
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null,skuId,"",stock.getNum(),wareOrderTaskEntity.getId(),wareId,1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(wareOrderTaskEntity.getId());
                    WareOrderTaskDetailTo lockedTo = new WareOrderTaskDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity,lockedTo);
                    stockLockedTo.setDetailIds(lockedTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    break;
                }else {
                    //当前仓库锁失败，重试下一个仓库
                }
            }
            if (!skuStocked) {
                //当前商品所有仓库都没有锁柱
                throw new NoStockException(skuId);
            }
        }

        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        //库存工作单的id
        Long id = to.getId();
        WareOrderTaskDetailTo detailIds = to.getDetailIds();
        Long skuId = detailIds.getSkuId();
        Long detailIdsId = detailIds.getId();
        //先查询数据库关于这个订单的锁定库存信息 没有-》锁定失败，库存回滚了，这种情况无需解锁
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailIdsId);
        if (byId!=null){
            //解锁
            Long orderId = to.getId();
            WareOrderTaskEntity testEntity = wareOrderTaskService.getById(orderId);
            String orderSn = testEntity.getOrderSn();
            //根据订单号查询订单状态  只有已取消才会解锁库存
            R orderStatus = orderFeignService.getOrderStatus(orderSn);
            if (orderStatus.getCode() == 0){
                OrderVo data = (OrderVo) orderStatus.getData("data", new TypeReference<OrderVo>() {});
                if (data==null||data.getStatus()==4){
                    //订单取消，解锁库存
                    unLockStock(skuId,detailIds.getWareId(),detailIds.getSkuNum(),detailIdsId);
                }
            }else {
                //消息拒绝之后重新放在队列里面
                throw new RuntimeException("远程服务失败");
            }
        }else {
            //无需解锁
        }
    }

    /**
     * 解锁库存
     */
    private void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        skuDao.unLockStock(skuId,wareId,num);
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(taskDetailId);
        wareOrderTaskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }


    @Data
    class SkuWareHasStock {
        private Long skuId;
        private List<Long> wareId;
        private Integer Num;
    }

}